// store/modules/user.js
import { login, logout, getUserInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import router, { resetRouter } from "@/router";

// 生成唯一的 tab ID
function generateTabId() {
  return "tab_" + Date.now() + "_" + Math.random().toString(36).substr(2, 9);
}

// 获取当前 tab ID，如果没有则创建一个新的
function getCurrentTabId() {
  let tabId = sessionStorage.getItem("current_tab_id");
  if (!tabId) {
    tabId = generateTabId();
    sessionStorage.setItem("current_tab_id", tabId);
  }
  return tabId;
}

// 获取当前 tab 的 token
function getTokenFromStorage() {
  try {
    const tabId = getCurrentTabId();
    const storageKey = `user-token-${tabId}`;
    return sessionStorage.getItem(storageKey);
  } catch (error) {
    console.error("获取token失败:", error);
    return null;
  }
}

// 设置当前 tab 的 token
function setTokenToStorage(token) {
  try {
    const tabId = getCurrentTabId();
    const storageKey = `user-token-${tabId}`;
    if (token) {
      sessionStorage.setItem(storageKey, token);
    } else {
      sessionStorage.removeItem(storageKey);
    }
  } catch (error) {
    console.error("设置token失败:", error);
  }
}

// 移除当前 tab 的 token
function removeTokenFromStorage() {
  try {
    const tabId = getCurrentTabId();
    const storageKey = `user-token-${tabId}`;
    sessionStorage.removeItem(storageKey);
  } catch (error) {
    console.error("移除token失败:", error);
  }
}
// 从本地存储获取用户信息
function getUserInfoFromStorage() {
  try {
    // 检查是否有 token
    const token = getTokenFromStorage();
    if (!token) return {};
    // 获取当前 tab ID
    const tabId = getCurrentTabId();
    // 从 sessionStorage 获取用户信息（更安全，关闭浏览器后清除）
    const storageKey = `user-info-${tabId}`;
    const userInfoStr = sessionStorage.getItem(storageKey);

    if (userInfoStr) {
      const userInfo = JSON.parse(userInfoStr);
      return userInfo;
    }
    return {};
  } catch (error) {
    console.error("解析用户信息失败:", error);
    return {};
  }
}

// 将用户信息保存到本地存储
function setUserInfoToStorage(userInfo) {
  try {
    const tabId = getCurrentTabId();
    const storageKey = `user-info-${tabId}`;

    sessionStorage.setItem(storageKey, JSON.stringify(userInfo));
  } catch (error) {
    console.error("保存用户信息失败:", error);
  }
}

// 从本地存储移除用户信息（基于当前 tab）
function removeUserInfoFromStorage() {
  try {
    const tabId = getCurrentTabId();
    const storageKey = `user-info-${tabId}`;

    sessionStorage.removeItem(storageKey);
  } catch (error) {
    console.error("移除用户信息失败:", error);
  }
}

const state = {
  token: getTokenFromStorage(),
  name: "",
  avatar: "",
  introduction: "",
  roles: [],
  userInfo: {}, // 初始化时从本地存储获取
  username: "",
};
// 在状态初始化后，手动设置用户信息
const initialUserInfo = getUserInfoFromStorage();

// 只有当获取到有效用户信息时才设置
if (initialUserInfo && Object.keys(initialUserInfo).length > 0) {
  state.userInfo = initialUserInfo;
  state.roles = initialUserInfo.roles || [];
  state.name = initialUserInfo.loginName || "";
  state.avatar = initialUserInfo.avatar || "";
  state.username = initialUserInfo.userName || "";
  state.introduction = initialUserInfo.introduction || "";
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
    setTokenToStorage(token);
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
    if (state.userInfo) {
      state.userInfo.avatar = avatar;
      setUserInfoToStorage(state.userInfo);
    }
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo;
    // 同时保存到本地存储
    if (userInfo) {
      setUserInfoToStorage(userInfo);

      // 同步更新其他相关字段
      state.name = userInfo.loginName || "";
      state.avatar = userInfo.avatar || "";
      state.username = userInfo.userName || "";
      state.introduction = userInfo.introduction || "";
      state.roles = userInfo.roles || [];
    }
  },
  SET_USERNAME: (state, username) => {
    state.username = username;
    if (state.userInfo) {
      state.userInfo.userName = username;
      setUserInfoToStorage(state.userInfo);
    }
  },
  CLEAR_USER_INFO: (state) => {
    state.token = "";
    state.name = "";
    state.avatar = "";
    state.introduction = "";
    state.roles = [];
    state.userInfo = {};
    state.username = "";
    removeUserInfoFromStorage();
    removeTokenFromStorage();
  },
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, checkForm, verifyKey } = userInfo;
    return new Promise((resolve, reject) => {
      login({
        username: username.trim(),
        password: password,
        code: checkForm,
        verifyKey: verifyKey,
      })
        .then((response) => {
          const { data } = response;
          if (data) {
            commit("SET_TOKEN", data.token);
            setToken(data.token);
            commit("SET_USER_INFO", data.user);

            // 从登录接口返回的用户信息中获取角色
            const roles = data.user.roles || [];
            if (!roles || roles.length === 0) {
              reject("登录返回的用户信息中没有角色信息");
              return;
            }
            commit("SET_ROLES", roles);
            commit("SET_USERNAME", data.user.userName);
            commit("SET_AVATAR", data.user.avatar);
            commit("SET_NAME", data.user.loginName);
            commit("SET_INTRODUCTION", data.user.introduction || "");

            resolve(data);
          } else {
            reject("登录失败");
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          commit("SET_TOKEN", "");
          commit("SET_ROLES", []);
          commit("CLEAR_USER_INFO");
          removeToken();
          resetRouter();
          commit("permission/RESET_ROUTES_STATE", null, { root: true });
          dispatch("tagsView/delAllViews", null, { root: true });

          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit, rootState }) {
    return new Promise((resolve) => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      commit("CLEAR_USER_INFO");
      removeToken();
      if (rootState && rootState.permission) {
        commit("permission/RESET_ROUTES_STATE", [], { root: true });
      }
      resolve();
    });
  },

  // get user info
  getInfo({ commit, state }, userId) {
    return new Promise((resolve, reject) => {
      getUserInfo({ userId })
        .then((response) => {
          const { data } = response;
          if (!data) {
            reject("获取用户信息失败");
            return;
          }
          commit("SET_TOKEN", data.token);
          setToken(data.token);
          commit("SET_USER_INFO", data.user);

          // 从登录接口返回的用户信息中获取角色
          const roles = data.user.roles || [];
          if (!roles || roles.length === 0) {
            reject("登录返回的用户信息中没有角色信息");
            return;
          }
          commit("SET_ROLES", roles);
          commit("SET_USERNAME", data.user.userName);
          commit("SET_AVATAR", data.user.avatar);
          commit("SET_NAME", data.user.loginName);
          commit("SET_INTRODUCTION", data.user.introduction || "");
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
};
export { getUserInfoFromStorage, getTokenFromStorage };
export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
